package com.vastcm.stuhealth.client.framework.report.service;

import java.io.File;
import java.sql.SQLException;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;

import com.vastcm.stuhealth.client.framework.report.IJasperReportService;
import com.vastcm.stuhealth.client.utils.PathUtil;

public class JasperReportService implements IJasperReportService {

	private SessionFactory sessionFactory;

	private String JasperReportPath;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession(boolean isNewSession) {
		try {
			return getSessionFactory().getCurrentSession();
		} catch (Exception e) {
		}
		return getSessionFactory().openSession();
	}

	public JasperPrint getJasperPrint(String jasperFilePath, Map<String, Object> params) throws JRException, SQLException {
		//获取路径和数据库连接
		JasperReport jasperReport = null;
		if (System.getenv("localProjectDebug") != null) {
			if (JasperReportPath == null) {
				JasperReportPath = PathUtil.getFilePathByClassRoot("jasper_report") + File.separator;
			}
			jasperReport = (JasperReport) JRLoader.loadObject(JasperReportPath + jasperFilePath);
		} else {
			jasperFilePath = "/jasper_report/" + jasperFilePath;
			jasperReport = (JasperReport) JRLoader.loadObject(getClass().getResourceAsStream(jasperFilePath));
		}
		//		final String jasperFilePathTemp = jasperFilePath;
		//		final Map<String, Object> paramsTemp = params;
		//		final JasperPrint print = null;
		//		getSession(true).doWork(new Work() {
		//
		//			@Override
		//			public void execute(Connection paramConnection) throws SQLException {
		//				try {
		//					print = JasperFillManager.fillReport(JasperReportPath + jasperFilePathTemp, paramsTemp, paramConnection);
		//				} catch (JRException e) {
		//					e.printStackTrace();
		//				}
		//			}
		//		});
		if (params != null && !params.containsKey("p_SUBREPORT_DIR")) {
			params.put("p_SUBREPORT_DIR", "jasper_report/");
		}
		ConnectionProvider connectionProvider = ((SessionFactoryImplementor) sessionFactory).getConnectionProvider();
		JasperPrint print = JasperFillManager.fillReport(jasperReport, params, connectionProvider.getConnection());
		return print;
	}
}